import User from "../model/user";
import ApiError from "../error/ApiError";
import ApiErrorNames from "../error/ApiErrorNames";

class UserController {
  static async getAllUser(ctx) {
    let user = await User.find({});
    if (user) {
      ctx.body = user;
    } else {
      throw new ApiError(ApiErrorNames.UserIsNull);
    }
  }

  static async getUserById(ctx) {
    let userName = ctx.query.userName; //get parm
    let user = await User.findOne({ userName: userName });
    if (user) {
      ctx.body = user;
    } else {
      throw new ApiError(ApiErrorNames.UserNotExist);
    }
  }

  static async saveUser(ctx) {
    let request = ctx.request.body; //post body
    console.log("-----request-----", request);
    if (!request.userName) {
      throw new ApiError(ApiErrorNames.UserNameNotNull);
    }
    let user = new User({
      ...request,
    });
    console.log("----user-----", user);
    user = await user.save();
    ctx.body = user;
  }
}

export default UserController;
